package com.haierCamera.customapplication.ui.main;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.haierCamera.customapplication.BaseActivity;
import com.haierCamera.customapplication.R;
import com.haierCamera.customapplication.api.ApiService;
import com.haierCamera.customapplication.databinding.HzklActivityDeviceEditBinding;
import com.haierCamera.customapplication.ui.business.Business;
import com.haierCamera.customapplication.utils.BitmapUtils;
import com.haierCamera.customapplication.utils.ResourceConvertUtils;
import com.haierCamera.customapplication.utils.android.HttpErrorProcess;
import com.haierCamera.customapplication.utils.glide.Glide4Engine;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.inject.Inject;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import dagger.Lazy;

public class HZKLCameraDeviceEditActivity extends BaseActivity {

    HzklActivityDeviceEditBinding binding;
    private static final int REQUEST_CODE_CHOOSE = 0x0101;

    @Inject
    Lazy<HttpErrorProcess> httpErrorProcessLazy;
    @Inject
    ApiService apiService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.hzkl_activity_device_edit);

        binding.imgReturn.setOnClickListener((v)->{
            finish();
        });

        binding.layout2.setOnClickListener((v)->{
            startActivityForResult(new Intent(HZKLCameraDeviceEditActivity.this
                    ,HZKLEditCameraNameActivity.class)
                    .putExtra("name",getIntent().getStringExtra("name"))
                    .putExtra("accountDeviceId",getIntent().getStringExtra("accountDeviceId"))
                    ,10000);
        });

        binding.layout1.setOnClickListener((v)->{
            upIcon();
        });

        binding.tvDeviceName.setText(getIntent().getStringExtra("name"));
        binding.tvSerialName.setText(getIntent().getStringExtra("sn"));
        if (getIntent().getStringExtra("picture")!=null
                && !getIntent().getStringExtra("picture").equals("")) {
            RequestOptions coverRequestOptions = new RequestOptions()
                    .diskCacheStrategy(DiskCacheStrategy.NONE)//不做磁盘缓存
                    .skipMemoryCache(true);//不做内存缓存

            Glide.with(this)
                    .load(getIntent().getStringExtra("picture"))
                    .apply(coverRequestOptions)
                    .into(binding.ivDeviceImg);
        }
        binding.ivNameCopy.setOnClickListener((v)->{
            //获取剪贴板管理器：
            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
// 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", "" + getIntent().getStringExtra("sn"));
// 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
            toast("复制到粘贴板");
        });

        getDeviceModel();
    }

    private void getDeviceModel(){
        Business.getInstance().getDeviceModel(getIntent().getStringExtra("sn"),new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                if(msg.what == 0) {
                    Bundle b = (Bundle) msg.obj;
                    String model =  b.getString("model");
                    binding.tvRight3.setText(model);
                }
            }
        });
    }

    private void upIcon() {
        Set<MimeType> set = new HashSet<>();
        set.add(MimeType.JPEG);
        set.add(MimeType.PNG);
        set.add(MimeType.BMP);
        processWithPermission(() -> processWithPermission(() -> {
            Matisse.from(HZKLCameraDeviceEditActivity.this)
                    .choose(set)
                    .countable(true)
                    .spanCount(3)
                    .capture(true)
                    .captureStrategy(new CaptureStrategy(true, "com.haierCamera.customapplication.fileProvider"))
                    // .theme(R.style.MatisseStyle)
                    .maxSelectable(1)
                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                    .thumbnailScale(0.85f)
                    .imageEngine(new Glide4Engine())
                    .forResult(REQUEST_CODE_CHOOSE);

        }, Manifest.permission.CAMERA), Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE);
    }

    public void uploadCoverPic(String devId,String base64,String channel) {
        ResourceConvertUtils.convertToResource(apiService.upLoadCoverPic(base64,devId,channel))
                .observe(this, resource -> {
                    assert resource != null;
                    switch (resource.status) {
                        case ERROR:
                            Log.i("TAG","error-" + resource.errorCode  + "/" + resource.toString());
                            httpErrorProcessLazy.get().process(resource);
                            dismissLoadingDialog();
                            break;
                        case SUCCESS:
                            dismissLoadingDialog();
                            RequestOptions coverRequestOptions = new RequestOptions()
                                    .diskCacheStrategy(DiskCacheStrategy.NONE)//不做磁盘缓存
                                    .skipMemoryCache(true);//不做内存缓存

                            Glide.with(this)
                                    .load(resource.data.url)
                                    .apply(coverRequestOptions)
                                    .into(binding.ivDeviceImg);

                            break;
                        case LOADING:
                            break;

                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 10000:
                    binding.tvDevice.setText(data.getExtras().getString("name"));
                    break;
                case  REQUEST_CODE_CHOOSE:
                    showLoadingDialog();


                    try {
                        List<Uri> mUri = Matisse.obtainResult(data);
                        Bitmap picBitmap= MediaStore.Images.Media.getBitmap(this.getContentResolver(),mUri.get(0));
                        String base64_s = BitmapUtils.getBitmapStrBase64(picBitmap);
                        Log.i("TAG", "base64-" + base64_s);
                        uploadCoverPic(getIntent().getStringExtra("sn"),base64_s,"0");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
                    default:
                        break;
            }
        }
    }
}
